package net.midnighttd.game.view;

import net.midnighttd.game.entity.Tower;
import net.midnighttd.engine.entity.Entity;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.util.List;

/**
 * Author: Adam Scarr
 * Date: 23/04/2009
 * Time: 8:50:00 PM
 */
public class TowerDetail extends EntityDetail {
    private final MainUI ui;

    public TowerDetail(MainUI mui, final Tower tower) {
        super(tower);

        this.ui = mui;

        JPanel wrapper = new JPanel();
        wrapper.setLayout(new BorderLayout());
        wrapper.setBackground(getBackground());

        JPanel details = new JPanel();
        details.setBackground(getBackground());
        details.setLayout(new GridLayout(5,2));
        details.add(new JLabel("Damage: "));
        details.add(new JLabel(Integer.toString(tower.getDamage()) + " hp"));
        details.add(new JLabel("Reload: "));
        details.add(new JLabel(trunc(tower.getSpeed()) + " sec"));
        details.add(new JLabel("DPS: "));
        details.add(new JLabel(trunc(tower.getDamage() / tower.getSpeed())));
        details.add(new JLabel("Range: "));
        details.add(new JLabel(trunc(tower.getRange()) + " squares"));
        details.add(new JLabel("Cost: "));
        details.add(new JLabel("$" + Integer.toString(tower.getCost())));
        wrapper.add(details, BorderLayout.NORTH);
        add(wrapper, BorderLayout.CENTER);


        if(tower.isActive()) {
            List<String> upgrades = tower.getUpgrades();
            JPanel upgradePanel = new JPanel();

            upgradePanel.setBackground(getBackground());
            upgradePanel.setLayout(new GridLayout(upgrades.size(),1));

            for(final String upgradeName: upgrades) {
                ThemedButton upgrade = new ThemedButton(upgradeName);
                upgrade.addActionListener(new ActionListener() {
                    public void actionPerformed(ActionEvent e) {
                        if(ui.getGame().getMoney() > tower.getUpgradeCost(upgradeName)) {
                            Tower newTower = (Tower)ui.getGame().getEntityManager().createEntityAt(tower.getX(), tower.getY(), upgradeName);
                            ui.getGame().getEntityManager().removeActiveEnt(tower);
                            ui.getTowerSelector().displayEntity(newTower);
                        }
                    }
                });
                upgradePanel.add(upgrade);
            }

            add(upgradePanel, BorderLayout.SOUTH);
        }
    }

    private String trunc(double x) {
        return Double.toString(Math.floor(x*100)/100);
    }
}
